package org.btik.video.server.push.udp;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.btik.context.thread.SystemControlAble;
import org.btik.video.server.push.VideoChannelFactory;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import static org.btik.video.server.device.udp2.NewUDPDeviceChannel.SN_LEN;

/**
 * @author lustre
 * @since 2023/4/27 10:56
 */
public class RawUdpVideoServer extends Thread implements SystemControlAble {
    private volatile boolean runFlag = true;

    private final Log log = LogFactory.getLog(RawUdpVideoServer.class);

    private int pushPort;

    private DatagramSocket serverSocket;


    private VideoChannelFactory videoChannelFactory;


    public void setPushPort(int pushPort) {
        this.pushPort = pushPort;
    }

    public void setVideoChannelFactory(VideoChannelFactory videoChannelFactory) {
        this.videoChannelFactory = videoChannelFactory;
    }

    @Override
    public void run() {
        log.info("RawUdp video push server start");
        try (DatagramSocket serverSocket = new DatagramSocket(pushPort)) {
            this.serverSocket = serverSocket;
            byte[] buffer = new byte[32];
            DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
            while (runFlag) {
                serverSocket.receive(datagramPacket);
                int length = datagramPacket.getLength();
                if (length < SN_LEN) {
                    continue;
                }
                RawUdpVideoChannel rawUdpVideoChannel = videoChannelFactory.getRawUdpVideoChannel(new String(buffer, 0, SN_LEN));
                if (rawUdpVideoChannel == null) {
                    continue;
                }
                rawUdpVideoChannel.setRawUdpVideoServer(this);
                rawUdpVideoChannel.setAddress(datagramPacket.getAddress(), datagramPacket.getPort());


            }
        } catch (IOException e) {
            log.error("", e);
        }
    }

    void sendFrame(DatagramPacket datagramPacket) {
        try {
            serverSocket.send(datagramPacket);
        } catch (IOException e) {
            log.error("", e);
        }
    }


    @Override
    public void shutdown(String msg) {
        if (isAlive() && runFlag) {
            if (!serverSocket.isClosed()) {
                serverSocket.close();
            }
            runFlag = false;
        }
    }
}
